import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('../views/Layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '系统概览' }
      },
      {
        path: 'sentences',
        name: 'Sentences',
        component: () => import('../views/Sentences.vue'),
        meta: { title: '句子管理' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/Users.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'recordings',
        name: 'Recordings',
        component: () => import('../views/Recordings.vue'),
        meta: { title: '录音管理' }
      },
      {
        path: 'assignments',
        name: 'Assignments',
        component: () => import('../views/Assignments.vue'),
        meta: { title: '句子分配' }
      }
    ]
  },
  {
    path: '*',
    redirect: '/dashboard'
  }
]

const router = new VueRouter({
  routes
})

// 处理路由导航，避免NavigationDuplicated错误
const safeNavigate = (router, to, next) => {
  // 如果目标路径与当前路径相同，直接调用next()避免重复导航
  if (router.currentRoute.fullPath === (typeof to === 'string' ? to : to.path)) {
    next()
    return
  }
  
  // 否则进行导航，并捕获可能的错误
  next(to)
}

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated
  const user = store.getters.user
  
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要认证但未登录，重定向到登录页
    if (!isAuthenticated) {
      safeNavigate(router, {
        path: '/login',
        query: { redirect: to.fullPath }
      }, next)
    } 
    // 已登录但不是管理员，登出并重定向到登录页
    else if (!user || user.role !== 'admin') {
      store.dispatch('logout')
      safeNavigate(router, {
        path: '/login',
        query: { redirect: to.fullPath }
      }, next)
      Vue.prototype.$errorMessage('您没有管理员权限')
    } 
    // 已登录且是管理员，允许访问
    else {
      next()
    }
  } else {
    // 不需要认证的路由，如果已登录且访问登录页则重定向到首页
    if (isAuthenticated && to.path === '/login') {
      safeNavigate(router, { path: '/' }, next)
    } else {
      next()
    }
  }
})

export default router 